package ink.carnation.imtalk.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {
    @Value("${JWT.expire}")
    public Long EXPIRE_TIME;//默认过期时间为半小时
    @Value("${JWT.secret}")
    private String SECRET;

    /**
     * 生成token
     *
     * @param userId
     * @param currentTime
     * @return
     */
    public String sign(Integer userId, Long currentTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        Date expireTime = new Date(currentTime + EXPIRE_TIME);
        String token = JWT.create()
                .withHeader(map)
                .withSubject(String.valueOf(userId))
                .withExpiresAt(expireTime)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public Boolean verity(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        Date expireTime = verify.getExpiresAt();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (expireTime.before(new Date())) {
            log.info("token已过期");
            //token过期了
            return false;
        }
        log.info("token认证通过: " + "id: " + verify.getSubject() + "过期时间：" + sdf.format(expireTime));
        return true;
    }

    public static Integer getUserId(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return Integer.valueOf(decodedJWT.getSubject());
    }
}
